package domo1;

import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.*;
import java.text.MessageFormat;
import java.util.Scanner;

public class dataSource {
    public static void main(String[] args) {

       //定义MySQL数据源对象
        MysqlDataSource mysqlDataSource=new MysqlDataSource();
        //设计数据库连接
        mysqlDataSource.setURL("jdbc:mysql://127.0.0.1:3306/java?characterEncoding" + "=utf8&allowPublicKeyRetrieval=true&useSSL=false");
        //连接数据库
        mysqlDataSource.setUser("root");
        mysqlDataSource.setPassword("123456");
        //定义JDBC数据原对象
        DataSource dataSource=mysqlDataSource;
        ResultSet resultSet=null;
        //定义SQL执行对象
        PreparedStatement statement=null;
        //数据库连接对象
        Connection connection=null;
        try {
            //通过数据源获取数据库连接
            connection= dataSource.getConnection();
            //定义SQL语句
            String sql="select id,name,chinese,math,english from exam where name=?";
            //预处理SQL语句
           statement= connection.prepareStatement(sql);
            //接收查询名称信息
            System.out.println("输入名称");
            Scanner scanner=new Scanner(System.in);
            String Inname= scanner.next();
            //用真实值替换占位符
            statement.setString(1,Inname);
            //收集结果集
            resultSet=statement.executeQuery();
            while (resultSet.next()){
                int id = resultSet.getInt(1);
                String name = resultSet.getString(2);
                int chinese=resultSet.getInt(3);
                int math=resultSet.getInt(4);
                int english=resultSet.getInt(5);
                System.out.println(MessageFormat.format("id={0},name={1},chinese={2},math={3},english={4}",id,name,chinese,math,english));
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        finally {
            //释放结果集
            if (resultSet != null) {
                try{
                    resultSet.close();
                }
                catch (SQLException e){
                    e.printStackTrace();
                }
            }
            //释放statement
            if (statement !=null){
                try {
                    statement.close();
                }
                catch (SQLException e){
                    e.printStackTrace();
                }
            }
            //断开连接
            if (connection !=null){
                try {
                    connection.close();
                }
                catch (SQLException e){
                    e.printStackTrace();
                }
            }
        }

    }
}
